﻿///***************************************************************
/// 시  스  템 : Updms.Fit
/// 단위시스템 : FIT
/// 계      층 : Presentation Layer
/// 프로그램명 : Fit3011p
/// 파  일  명 : Fit3011p.aspx.cs
/// 설      명 : 운동수행결과 팝업
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2014-05-29 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web;

using SMFramework.Configuration;
using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.Dac;
using Base.AppFramework;
using Base.AppFramework.Web.UI.CommandBar;

using Updms.Fit.Exe;
using System.Web.UI.WebControls;

namespace Updms.Fit
{
	public partial class Fit3011p : Updms.Common.BaseClass.PageBase
	{
		#region 콘트롤

		public static readonly string PID = "Fit3011p";
		Global global = new Global();

		private string training_id = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				OnPageLoad();
				if (CheckViewAuth())
				{
					SelectProcess();
				}
			}
		}

		//OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region CheckViewAuth

		//인증검사
		private bool CheckViewAuth()
		{
			using (AccessCheck access = new AccessCheck())
			{
				//접근권한 체크
				if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
				{
					Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					return false;
				}
				return true;
			}
		}

		#endregion

		#region SetInit

		// SetInit
		private void SetInit()
		{
			if (Request.QueryString["training_id"] != null)
			{
				training_id = Server.UrlDecode(Request.QueryString["training_id"].ToString().Trim());
			}
		}

		#endregion

		#region SelectProcess, SetSummary, SetSummaryShowAll

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_training_id", typeof(int), training_id);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//DataTable명 지정
			string[] dt_name = new string[] {	"FIT3011P_MASTER",
												"FIT3011P_RESULT",
												"FIT3011P_DISTINCT_PARTS"
											};

			using (Fit3011p_NT _Fit3011p_NT = new Fit3011p_NT())
			{
				lo_ds.Merge(_Fit3011p_NT.GetTrainingResultByTrainingId(lo_dp, dt_name));
			}

			//마스터
			string dt_name_master = dt_name[0];
			if (DataSetUtil.CheckTable(lo_ds, dt_name_master))
			{
				if (DataSetUtil.GetRowCount(lo_ds, dt_name_master) > 0)
				{
					lbl_training_dt.Text = DataSetUtil.GetFldStr(lo_ds, dt_name_master, "Training_Dt");
					lbl_training_time.Text = DataSetUtil.GetFldStr(lo_ds, dt_name_master, "Training_Time");
					lbl_location.Text = DataSetUtil.GetFldStr(lo_ds, dt_name_master, "Location");
					lbl_training_part.Text = DataSetUtil.GetFldStr(lo_ds, dt_name_master, "Training_Part_Nm");
				}
			}

			string dt_name_parts = dt_name[1];
			if (DataSetUtil.CheckTable(lo_ds, dt_name_parts))
			{
				GridView1.DataSource = lo_ds.Tables[1];
				GridView1.DataBind();

				SetSummary(lo_ds.Tables[1], lo_ds.Tables[2]);
			}
		}

		//구글저장용 요약정보
		private void SetSummary(DataTable dt_result, DataTable dt_distinct_parts)
		{
			StringBuilder sb = new StringBuilder();
			
			DataTable dt_memo = new DataTable();
			dt_memo.Columns.Add("Training_Part_Nm");
			dt_memo.Columns.Add("Training_Nm");
			dt_memo.Columns.Add("Action_Weight");
			dt_memo.Columns.Add("Action_Count");
			dt_memo.Columns.Add("Set_Count");
			dt_memo.Columns.Add("Remark");
			DataRow dr;

			for (int i = 0; i < dt_distinct_parts.Rows.Count; i++)
			{
				dt_memo.Clear();
				string trainingPart = dt_distinct_parts.Rows[i]["Training_Part"].ToString();
				string trainingPartNm = dt_distinct_parts.Rows[i]["Training_Part_Nm"].ToString();
				
				string ls_training_nm = ""; //운동명
				string ls_action_weight = ""; //중량(output)
				double ld_action_weight = 0.0; //중량
				string ls_action_count = ""; //반복횟수
				string ls_set_count = ""; //세트
				string ls_remark = ""; //비고

				//소계,총계는 제외
				DataRow[] drColumns = dt_result.Select("Training_Part = '" + trainingPart + "' AND View_Order NOT LIKE 'B%'");

				foreach (DataRow drTemp in drColumns)
				{
					dr = dt_memo.NewRow();
					dr["Training_Part_Nm"] = drTemp["Training_Part_Nm"].ToString();
					dr["Training_Nm"] = drTemp["Training_Nm"].ToString();
					dr["Action_Weight"] = drTemp["Action_Weight"].ToString();
					dr["Action_Count"] = drTemp["Action_Count"].ToString();
					dr["Set_Count"] = drTemp["Set_Count"].ToString();
					dr["Remark"] = drTemp["Remark"].ToString();

					dt_memo.Rows.Add(dr);
					dt_memo.AcceptChanges();
				}

				sb.AppendLine("●" + trainingPartNm);
				
				for (int j = 0; j < dt_memo.Rows.Count; j++)
				{
					ls_training_nm = dt_memo.Rows[j]["Training_Nm"].ToString();
					ld_action_weight = Convert.ToDouble(dt_memo.Rows[j]["Action_Weight"]);
					ls_action_count = dt_memo.Rows[j]["Action_Count"].ToString();
					ls_set_count = dt_memo.Rows[j]["Set_Count"].ToString();
					ls_remark = dt_memo.Rows[j]["Remark"].ToString();

					ls_action_weight = (ld_action_weight > 0) ? "- " + ld_action_weight.ToString("#,##0.#") + "kg:" : "- ";

					sb.AppendLine(ls_training_nm);
					sb.Append(ls_action_weight);
					sb.Append(ls_action_count + "회");
					sb.AppendLine("x" + ls_set_count);

					//비고
					if (ls_remark.Length > 2)
					{
						sb.AppendLine(ls_remark);
					}
				}
			}

			//마지막 라인 제거
			txt_summary.Text = sb.ToString().Substring(0, sb.ToString().LastIndexOf(System.Environment.NewLine));
		}

		//전체보기 설정
		private void SetSummaryShowAll(bool is_all)
		{
			string[] aSummary = txt_summary.Text.Split(new String[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
			
			txt_summary.Style.Remove("height");

			if (is_all)
			{
				txt_summary.Style.Add("height", (aSummary.Length * 17).ToString() + "px");
			}
			else
			{
				txt_summary.Style.Add("height", "120px");
			}
		}


		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "BA001": //소계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "BA002": //총계
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						//총계 colspan
						e.Row.Cells[1].ColumnSpan = 2;
						e.Row.Cells[2].Visible = false;
						break;
					default:
						break;
				}
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 1); //Training_Part_Nm
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region 버튼이벤트

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_training_id", typeof(int), training_id);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			//DataTable명 지정
			string[] dt_name = new string[] {	"FIT3011P_MASTER",
												"FIT3011P_PARTS"
											};

			using (Fit3011p_NT _Fit3011p_NT = new Fit3011p_NT())
			{
				lo_ds.Merge(_Fit3011p_NT.GetTrainingResultByTrainingId(lo_dp, dt_name));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, 1, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SetSummaryShowAll(cb_list_all.Checked);
		}

		#endregion

	}
}